<template>
  <div>
    <el-button type="primary" @click="dialogVisible = true">添加图书</el-button>
    <el-table :data="books" style="width: 100%">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="title" label="书名"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="copies" label="数量"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="deleteBook(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="'添加图书'" :visible.sync="dialogVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="书名" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="copies">
          <el-input-number v-model="form.copies" :min="1"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  name: 'BookManagement',
  data() {
    return {
      dialogVisible: false,
      form: {
        title: '',
        author: '',
        copies: 1
      },
      rules: {
        title: [
          { required: true, message: '请输入书名', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ],
        copies: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapState(['books'])
  },
  methods: {
    ...mapActions(['addBook', 'deleteBook']),
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.addBook(this.form)
          this.form = { title: '', author: '', copies: 1 }
          this.dialogVisible = false
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>